import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'

declare var $: any
declare var BMap: any
declare var toWGS84: any
declare var toMapPoint: any

const railStyle = {
  strokeColor: 'blue',
  fillColor: 'red',
  strokeWeight: 1,
  strokeOpacity: 0.2,
  fillOpacity: 0.2
}
@Component({
  selector: 'sa-fence-edit',
  templateUrl: './fence-edit.component.html',
  styleUrls: ['./fence-edit.component.css']
})
export class FenceEditComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      fenceName: {
        validators: {
          notEmpty: {
            message: '请填写围栏名称'
          }
        }
      },
      companyName: {
        validators: {
          notEmpty: {
            message: '请选择公司'
          }
        }
      },
      businessType: {
        validators: {
          notEmpty: {
            message: '请选择行业类型'
          }
        }
      },

      lng: {
        validators: {
          notEmpty: {
            message: '请填写经度'
          }
        }
      },
      lat: {
        validators: {
          notEmpty: {
            message: '请填写纬度'
          }
        }
      },

      radius: {
        validators: {
          notEmpty: {
            message: '请填写围栏半径'
          }
        }
      }
    }
  }

  page: any = {
    id: '',
    fenceName: '',
    companyName: '',
    companyId: '',
    businessType: '',
    radius: '500',
    lng: '',
    lat: '',
    remark: '',
    isEnable: 1
  }

  businessTypeList: any[] = [] //行业类型
  companyInfo: any = {} //公司信息
  page_title: string = '新增'
  pageType: string = 'new'

  curPage: number = 0 //缓存页码使用
  rowId = null

  isEnableFence: any = true // 是否同步

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.rowId = queryParams.id
      this.pageType = queryParams.type
      this.curPage = queryParams.nowPage
    })
    this.businessTypeList = businessTypeList
  }
  //行业类型选择
  businessTypeChange(e) {
    this.page.businessType = e
  }

  timeOut: any = ''
  companySelected(data) {
    $('button[type="submit"]').removeAttr('disabled')
    this.page.companyId = data.companyId || ''
    this.page.companyName = data.companyName || ''
  }

  //from表单提交
  onSubmit() {
    $('#companyForm').bootstrapValidator('validate') //开启验证
    let isValid = $('#companyForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.update()
    }
  }

  //from表单提交
  update() {
    let reqdata: string = '',
      url = 'factoryFence/addFactoryFence'
    if (this.pageType === 'new') {
      for (let item in this.page) {
        if (this.page[item] || this.page[item] === 0) {
          if (!reqdata) {
            reqdata += item + '=' + this.page[item]
          } else {
            reqdata += '&' + item + '=' + this.page[item]
          }
        }
      }
    } else if (this.pageType === 'update') {
      for (let item in this.page) {
        reqdata += '&' + item + '=' + this.page[item]
      }
    }
    this.jsonApiService.http(url, reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      this.router.navigate(['/data-statistics/task/fence'], {
        queryParams: {
          nowPage: this.curPage
        }
      })
    })
  }
  //返回资源列表页
  goBack() {
    this.router.navigate(['/data-statistics/task/fence'], {
      queryParams: {
        nowPage: this.curPage
      }
    })
  }

  ngOnInit() {
    this.initMap()
    //初始化from表单
    this.isEnableFence = true // 是否开启围栏

    if (this.pageType === 'update') {
      this.page_title = '编辑'
      let reqdata = 'id=' + this.rowId

      this.jsonApiService.http('factoryFence/getFactoryFenceDetailById', reqdata).subscribe(data => {
        if (data.success) {
          for (let item in this.page) {
            this.page[item] = data.data[item]
          }
          if (data.data.isEnable === 0) {
            this.isEnableFence = false
          }
          this.loadMarker()
        } else {
          this.jsonApiService.message(data.message)
        }
      })
    }
  }
  // 是否同步
  isEnableFenceClick() {
    this.isEnableFence = !this.isEnableFence
    this.page.isEnable = this.isEnableFence ? 1 : 0
  }

  // 打开地图
  showMap() {
    this.loadMarker()
  }
  // 初始化地图
  MAP: any
  initMap() {
    let that = this
    var map = new BMap.Map('baiduMap', { enableMapClick: false })
    that.MAP = map
    const point = new BMap.Point(116.404, 39.915) //创建点坐标
    map.centerAndZoom(point, 14) //初始化地图，设置中心点坐标和地图级别
    map.enableScrollWheelZoom()
    map.addEventListener('click', function (e) {
      const marker = new BMap.Marker(e.point) // 创建标注
      const circle = new BMap.Circle(e.point, that.page.radius, railStyle) //创建圆
      // map.centerAndZoom(e.point, 14)
      map.clearOverlays()
      map.addOverlay(marker)
      map.addOverlay(circle)
      const WGS84point = toWGS84({ lng: e.point.lng, lat: e.point.lat })
      that.page.lng = WGS84point.lng
      that.page.lat = WGS84point.lat
    })
    this.initBmapAutoSearch(map, that)
  }
  // 地图打点-渲染
  loadMarker() {
    if (this.page.lng && this.page.lat) {
      let point = toMapPoint({ lng: this.page.lng, lat: this.page.lat })
      let mapPoint = new BMap.Point(point.lng, point.lat)
      this.MAP.centerAndZoom(mapPoint, 16)
      let marker = new BMap.Marker(point) // 创建标注

      const circle = new BMap.Circle(mapPoint, this.page.radius, railStyle) //创建圆
      this.MAP.clearOverlays()
      this.MAP.addOverlay(marker)
      this.MAP.addOverlay(circle)
    }
  }
  // 百度地图自动检索功能
  initBmapAutoSearch(map, self) {
    //建立一个自动完成的对象
    let autoSearch = new BMap.Autocomplete({ input: 'suggestId', location: map })
    autoSearch.addEventListener('onhighlight', function (e) {
      //鼠标放在下拉列表上的事件
      var str = ''
      var _value = e.fromitem.value
      var value = ''
      if (e.fromitem.index > -1) {
        value = _value.province + _value.city + _value.district + _value.street + _value.business
      }
      str = 'FromItem<br />index = ' + e.fromitem.index + '<br />value = ' + value
      value = ''
      if (e.toitem.index > -1) {
        _value = e.toitem.value
        value = _value.province + _value.city + _value.district + _value.street + _value.business
      }
      str += '<br />ToItem<br />index = ' + e.toitem.index + '<br />value = ' + value
      document.getElementById('searchResultPanel').innerHTML = str
    })
    let myValue
    // 创建地址解析器实例
    var myGeo = new BMap.Geocoder()
    // 将地址解析结果显示在地图上,并调整地图视野
    autoSearch.addEventListener(
      'onconfirm',
      function (e) {
        //鼠标点击下拉列表后的事件
        let _value = e.item.value
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business
        document.getElementById('searchResultPanel').innerHTML =
          'onconfirm<br />index = ' + e.item.index + '<br />myValue = ' + myValue
        let local = new BMap.LocalSearch(map, {
          //智能搜索
          onSearchComplete: function (result) {
            // var pp = result.getPoi(0).point;    //获取第一个智能搜索的结果
            myGeo.getPoint(
              local.getResults().keyword,
              function (point) {
                if (point) {
                  var pointNew = new BMap.Point(point.lng, point.lat)

                  const circle = new BMap.Circle(pointNew, self.page.radius, railStyle) //创建圆
                  map.centerAndZoom(pointNew, 16)
                  map.clearOverlays()
                  map.addOverlay(new BMap.Marker(pointNew))
                  map.addOverlay(circle)
                } else {
                  alert('您选择地址没有解析到结果!')
                }
              },
              '北京市'
            )
          }.bind(this)
        })
        local.search(myValue)
      }.bind(this)
    )
  }
  suggestSearchBtn() {
    var that = this
    if (!$('#suggestId').val()) {
      that.jsonApiService.message('请先输入地址')
      return
    }
    // 创建地址解析器实例
    var myGeo = new BMap.Geocoder()
    // 将地址解析结果显示在地图上,并调整地图视野
    myGeo.getPoint(
      $('#suggestId').val(),
      function (point) {
        if (point) {
          var pointNew = new BMap.Point(point.lng, point.lat)
          const circle = new BMap.Circle(pointNew, that.page.radius, railStyle) //创建圆
          that.MAP.centerAndZoom(pointNew, 16)
          that.MAP.clearOverlays()
          that.MAP.addOverlay(new BMap.Marker(pointNew))
          that.MAP.addOverlay(circle)
        } else {
          alert('您选择地址没有解析到结果!')
        }
      },
      '全国'
    )
  }

  numberFilter() {
    const page = this.page
    page.radius = page.radius
      .replace(/^\.+|[^0-9\.]+/g, '')
      .replace(/\.+/g, '.')
      .replace(/^(0+)(\d+)?/g, (match, p1, p2) => {
        if (!p2) {
          return '0'
        }
        return p2
      })

    this.loadMarker()
  }
}
